package net.vistiyos.download;

import java.awt.Desktop;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

import net.vistiyos.modelo.Capitulo;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class PirateBay {
	
	private static String enlace;
	
	static public boolean getArchivoTorrent(Capitulo episodio) throws URISyntaxException{
		if(episodio==null){
			return false;
		}
		String query=episodio.getTemporada()+"x"+episodio.getCapitulo();
		query=query.replaceAll(" ", "+");
		try{
			URL url=new URL("http://thepiratebay.se/search/"+query+"/0/99/0");
			Document doc = Jsoup.connect(url.toString()).get();
			Elements rows = doc.select("#searchResult tr");
			int seed=0;
			for(int i=0;i<rows.size();i++){
				Element ele=rows.get(i);
				if(!ele.html().contains("<th>")){
					Elements cols=ele.children();
					if(Integer.parseInt(cols.get(2).text())>seed){
						seed=Integer.parseInt(cols.get(2).text());
						String html=cols.get(1).html();
						int ini=html.indexOf("<a href=\"magnet");
						int fin=html.indexOf('"', ini+11);
						enlace=html.substring(ini+9, fin);
					}
				}
			}
			Desktop.getDesktop().browse(new URI(enlace));
			return true;
		}catch(MalformedURLException ex){
			return false;
		}catch(IOException ex){
			return false;
		}
	}

}
